<template>
  <el-card class="news-container">
    <!-- 表格展示 -->
    <el-table :data="pageData" stripe>
      <el-table-column prop="title" label="新闻标题" width="300" />
      <el-table-column label="类别">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.type)">{{ formatTest(row.type) }}</el-tag> 
        </template>
      </el-table-column>
      <el-table-column label="浏览数">
        <template #default="{ row }">{{ formatViews(row.pageViews) }}</template>  
      </el-table-column>
      <el-table-column label="发布时间">
        <template #default="{ row }">{{ row.pastHours }}</template>  
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="toDetail(row.hid)">查看</el-button>
          <el-button 
            v-if="row.publisher == userId" 
            type="warning" 
            size="small" 
            @click="modify(row.hid)">
              修改
          </el-button>
          <el-button 
            v-if="row.publisher == userId" 
            type="danger" 
            size="small" 
            @click="handlerDelete(row.hid)">
              删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination 
      background
      class="custom-pagination" 
      v-model:current-page = "findNewsPageInfo.pageNum"
      v-model:page-size = "findNewsPageInfo.pageSize"
      @size-change = "getPageList"
      @current-change = "getPageList"
      :page-sizes = "[5,7,10]"
      layout = "prev, pager, next , ->, sizes, total"
      :total = "totalSize"/>
  </el-card>
</template>

<script setup>
/* 
import { emitter } from '@/utils/eventBus' */

import { ref, computed, onMounted, watch  } from 'vue';
import { getFindNewsPageInfo, getFindAllTypes, removeNewsByHid  } from "@/api/index"
import { useUserInfoStore } from '@/stores/userInfo'
import { findNewsTnameByTid } from '@/untils/business';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import { emitter } from '@/untils/evenBus'



//接收导航发布的新闻类型
emitter.on("news-type", (message)=>{
  console.log("接收news-type内容:" + JSON.stringify(message))
  findNewsPageInfo.value.type = message.newsType

  //getPageList()
})

//接收导航搜索框的关键字
emitter.on("search-key", (message)=>{
  findNewsPageInfo.value.keyWords = message.searchKey
  //getPageList()
})




const router = useRouter()

const userInfoStore = useUserInfoStore()
const userId = userInfoStore.uid
const nickName = userInfoStore.nickName


//启动页面，读数据，展示新闻
onMounted(()=>{
  getPageList()

  //console.log("onMounted... nickName1111=" + userInfoStore.nickName)
  //第一次登录时，把获取到的nickname发布给导航页
  emitter.emit('header-name',{
    headerName: nickName
  })
})


//启动页面查询新闻 
const findNewsPageInfo = ref(
  {
    keyWords: "", // 搜索标题关键字
    type: 0,           // 新闻类型
    pageNum: 1,        // 页码数
    pageSize: 10,     // 页大小
  }
)

//监听分页查询的输入参数，有变化，直接重新查询
watch(
  ()=>findNewsPageInfo.value,
  ()=>{getPageList()},
  {deep: true},
)

// 初始化请求分页列表数据
const totalSize = ref(0) //分页总数量

//初始化列表数据
const pageData = ref([{
    hid: null,
    pageViews: null,
    pastHours: null,
    publisher: null,
    title: "",
    type: null
}])

const getPageList = async () => {
  let result = await getFindNewsPageInfo(findNewsPageInfo.value)
  await getNewsType()
  pageData.value = result.pageInfo.pageData
  findNewsPageInfo.value.pageNum = result.pageInfo.pageNum
  findNewsPageInfo.value.pageSize = result.pageInfo.pageSize
  totalSize.value = + result.pageInfo.totalSize
}

//查询新闻分类方法
const typeOptions = ref([])
const getNewsType = async () => {
  let result = await getFindAllTypes()
  // tid=1 tname=新闻
  result.forEach((item)=>{
    let obj = {}
    obj.tid = item.tid
    obj.tname = item.tname
    typeOptions.value.push(obj)
  })
}

//浏览数格式化
const formatViews = (views)=> {
  return views > 10000 ? '1万+' : views
}
const formatTest = (views) => {
  return findNewsTnameByTid(views, typeOptions.value)
}
//查看新闻
const toDetail = (hid) => {
  router.push({ name: 'Detail', query:{hid}})
}
//修改新闻
const modify = (hid) => {
  router.push({ name: 'AddOrModifyNews', query:{hid}})
}
//删除新闻
const handlerDelete = async (hid) => {
  await removeNewsByHid(hid)
  ElMessage.success("删除这条新闻成功！")
  //要重新加载主页新闻信息
  getPageList()
}

const getTagType = (category) => {
  const types = { 1: 'success', 2: 'warning', 3: 'danger', 4: 'primary'}
  return types[category] || 'info'
}


</script>

<style lang='less' scoped>
.news-container {
  background: linear-gradient(135deg, #f8f8f9 0%, #f7f8f8 100%);

  .action-buttons {
    display: flex;
    gap: 8px;  
    flex-wrap: wrap;  
  }

  .custom-pagination {
    margin-top: 20px;
    justify-content: flex-end;  

    .el-pagination__jump { 
      margin-left: 12px; 
    } 

  }

  @media (max-width: 768px) {
    .el-button {
      margin: 3px;  
    }
  }
}
</style>